package com.qiaofang.collectmanage.dao.impl;

import com.alibaba.fastjson.JSONObject;
import com.qiaofang.collectmanage.dao.EsDAO;
import com.qiaofang.collectmanage.dao.constant.StatisticsConditionProperties;
import com.qiaofang.collectmanage.dao.elasticsearch.EsClient;
import com.qiaofang.collectmanage.dao.util.ConfigUtils;
import com.qiaofang.collectmanage.dao.util.DateUtils;
import com.qiaofang.collectmanage.stub.bean.ChannelSaleAndRentalDTO;
import com.qiaofang.collectmanage.stub.constants.BelongerEnum;
import com.qiaofang.collectmanage.stub.constants.CollectHouseTypeEnum;
import com.qiaofang.collectmanage.stub.constants.CollectTypeEnum;
import com.qiaofang.collectmanage.stub.constants.PlatFormEnum;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.range.Range;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Repository
public class EsDaoImpl implements EsDAO {
    private static final Logger logger = LoggerFactory.getLogger(EsDaoImpl.class);

    /**
     * 查询频道下出租出售情况
     * @return
     */
    @Override
    public List<ChannelSaleAndRentalDTO> queryChannelSaleAndRental(String platForm,String[] indexs,String[] types) {
        List<ChannelSaleAndRentalDTO> channelSaleAndRentalDTOs = new ArrayList<ChannelSaleAndRentalDTO>();
        try {
            QueryBuilder queryBuilderRental = QueryBuilders.boolQuery();
            TermsAggregationBuilder aggregationBuilders = null;
            if (PlatFormEnum.QIAOFANG.getValue().equals(platForm)) {
                aggregationBuilders = AggregationBuilders
                        .terms(StatisticsConditionProperties.GROUP_BY_CITY).field(StatisticsConditionProperties.CITY).size(97)
                        .subAggregation(AggregationBuilders.terms(StatisticsConditionProperties.GROUP_BY_SOURCE).field(StatisticsConditionProperties.SOURCE)
                                .subAggregation(AggregationBuilders.terms(StatisticsConditionProperties.GROUP_BY_TYPE).field(StatisticsConditionProperties.TYPE).size(2)
                                        .subAggregation(AggregationBuilders.range(StatisticsConditionProperties.GROUP_BY_CREATETIME).field(StatisticsConditionProperties.PUBLISHTIME)
                                                .addRange(StatisticsConditionProperties.TODAY, DateUtils.getDayStartDate().getTime(), DateUtils.getDayEndDate().getTime())
                                                .addUnboundedTo(StatisticsConditionProperties.ALL, DateUtils.getDayEndDate().getTime()))));
            } else {
                aggregationBuilders = AggregationBuilders
                        .terms(StatisticsConditionProperties.GROUP_BY_CITY).field(StatisticsConditionProperties.CITY).size(97)
                        .subAggregation(AggregationBuilders.terms(StatisticsConditionProperties.GROUP_BY_SOURCE).field(StatisticsConditionProperties.SOURCE)
                                .subAggregation(AggregationBuilders.terms(StatisticsConditionProperties.GROUP_BY_TYPE).field(StatisticsConditionProperties.COLLECTTYPE).size(2)
                                        .subAggregation(AggregationBuilders.range(StatisticsConditionProperties.GROUP_BY_CREATETIME).field(StatisticsConditionProperties.CREATETIME)
                                                .addRange(StatisticsConditionProperties.TODAY, DateUtils.getDayStartDate().getTime(), DateUtils.getDayEndDate().getTime())
                                                .addUnboundedTo(StatisticsConditionProperties.ALL, DateUtils.getDayEndDate().getTime()))));
            }


            SearchResponse searchResponseRental = EsClient.queryAggregationCondition(indexs, types, queryBuilderRental, aggregationBuilders);

            //获取聚合
            Terms terms = searchResponseRental.getAggregations().get(StatisticsConditionProperties.GROUP_BY_CITY);
            //遍历处理数据
            for (Terms.Bucket entry : terms.getBuckets()) {
                String city = (String) entry.getKey();
                Terms sourceTermss = entry.getAggregations().get(StatisticsConditionProperties.GROUP_BY_SOURCE);
                for (Terms.Bucket sourceTerm : sourceTermss.getBuckets()) {
                    String source = (String) sourceTerm.getKey();
                    long docCount = sourceTerm.getDocCount();
                    Terms typeTermss = sourceTerm.getAggregations().get(StatisticsConditionProperties.GROUP_BY_TYPE);
                    ChannelSaleAndRentalDTO channelSaleAndRentalDTO = new ChannelSaleAndRentalDTO();
                    channelSaleAndRentalDTO.setCity(city);
                    channelSaleAndRentalDTO.setSource(source);
                    channelSaleAndRentalDTO.setBelonger(BelongerEnum.PERSONAL.getValue());
                    channelSaleAndRentalDTO.setCollectHouseType(CollectHouseTypeEnum.RESIDENTIAL.getValue());
                    if (PlatFormEnum.QIAOFANG.getValue().equals(platForm)) {
                        channelSaleAndRentalDTO.setPlatform(PlatFormEnum.QIAOFANG.getValue());
                    } else {
                        channelSaleAndRentalDTO.setPlatform(PlatFormEnum.BEE.getValue());
                    }
                    for (Terms.Bucket typeTerm : typeTermss.getBuckets()) {
                        String type = (String) typeTerm.getKey();
                        long typeCount = typeTerm.getDocCount();
                        if (StatisticsConditionProperties.RENTALHOUSE.equals(type) ||  CollectTypeEnum.RENT.getValue().equals(type)) {
                            channelSaleAndRentalDTO.setRentalNum(typeCount);

                            Range createTermss = typeTerm.getAggregations().get(StatisticsConditionProperties.GROUP_BY_CREATETIME);
                            for (Range.Bucket createTimeTerm : createTermss.getBuckets()) {
                                if (StatisticsConditionProperties.TODAY.equals(createTimeTerm.getKey())) {
                                    channelSaleAndRentalDTO.setRentalTodayNum(createTimeTerm.getDocCount());
                                }
                            }
                        } else if (StatisticsConditionProperties.SALEHOUSE.equals(type) || CollectTypeEnum.SELL.getValue().equals(type)) {
                            channelSaleAndRentalDTO.setSaleNum(typeCount);
                            Range createTermss = typeTerm.getAggregations().get(StatisticsConditionProperties.GROUP_BY_CREATETIME);
                            for (Range.Bucket createTimeTerm : createTermss.getBuckets()) {
                                long todayNum = createTimeTerm.getDocCount();
                                if (StatisticsConditionProperties.TODAY.equals(createTimeTerm.getKey())) {
                                    channelSaleAndRentalDTO.setSaleTodayNum(todayNum);
                                }
                            }
                        }
                    }
                    channelSaleAndRentalDTOs.add(channelSaleAndRentalDTO);
                    logger.info("统计{}数据{}", platForm, channelSaleAndRentalDTO.toString());
                }
            }
        }catch (Exception e){
            logger.error("统计数据异常{}", e);
        }
        return channelSaleAndRentalDTOs;
    }
}
